package com.xiaomaoguai.fcp.pre.kepler.router.handler.handlercontext;

import com.xiaomaoguai.fcp.pre.kepler.router.buf.Buf;
import com.xiaomaoguai.fcp.pre.kepler.router.exception.RouterException;
import com.xiaomaoguai.fcp.pre.kepler.router.handler.api.HandlerContext;
import com.xiaomaoguai.fcp.pre.kepler.router.handler.handlers.TailHandler;
import com.xiaomaoguai.fcp.pre.kepler.router.router.RouterPipeline;
import org.apache.commons.lang3.builder.ToStringBuilder;

/**
 * tailcontext
 * pipe必备context
 * 主要负责生成返回报文操作
 * 责任链异常汇总处理
 *
 * @param <O>
 * @author DH
 */
public class TailContext<O> extends DefaultHandlerContext<Buf> implements HandlerContext<Buf> {

	private final static String handlerName = "TAIL";

	private O outParam;

	public TailContext(RouterPipeline<?, O> router, TailHandler<O> handler) {
		super(router);
		this.handler = handler;
	}

	public O getOutParam() {
		return outParam;
	}

	public void setOutParam(O outParam) {
		this.outParam = outParam;
	}

	/**
	 * tailHandler区别于其他handler
	 * 没有异步调用，nexthandler调用
	 */
	@Override
	public Buf invokeHandler() {
		invokeCurrentHandler();
		return getBuf();
	}

	@Override
	public String name() {
		return handlerName;
	}

	@Override
	public HandlerContext<Buf> getLast() {
		return this;
	}

	@Override
	public HandlerContext<?> getHandlerContext(String handlerName,Integer order) {
		if (handlerName.equals(name()))
			return this;
		else
			return null;
	}

	@Override
	public void fireExceptionCaught(RouterException e) {
		handler.exceptionCaught(e);
	}


	@Override
	public String toString() {
		return new ToStringBuilder(this)
				.append("outParam", outParam)
				.append("routerInfo", routerInfo)
				.append("handler", handler.getClass().getSimpleName())
				.append("handleResult", handleResult)
				.append("innerParam", innerParam)
				.toString();
	}
}
